//
//  HMStatusPickerView.swift
//  01-SinaWeibo
//
//  Created by 周英培 on 16/5/26.
//  Copyright © 2016年 周英培. All rights reserved.
//

/*
 系统自带的有点击头部tabbar 会自动会到顶部 但是有一个前提：只能包含一个view 此时 这里面既有UICollectionView 还有UITableView  所以要关闭一个 属性：scrollsToTop  是点击状态栏 而不是点击导航条 
 
 */
import UIKit

import SnapKit

//图片的间距
let pictureMargin : CGFloat = 3

//图片最大宽度
let maxWidth = ScreenWidth - 2 * margin

//单张图片的宽度
let itemWidth = (maxWidth - 2 * pictureMargin) / 3

let PICTURECELL = "pictureCell"


class HMStatusPickerView: UICollectionView {
    
    // s数据源
    var pictures : [HMPictureModel]? {
        
        didSet {
            
  //根据图片的大小更新约束
            let picSize = pictureSize()
            
           self.snp_updateConstraints { (make) in
            make.size.equalTo(picSize)
            }
            //数据发生变化 就刷新数据
            reloadData()
            
        }
        
    }


    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        //必须是流水布局
        let layout = UICollectionViewFlowLayout()
        
        //设置行间距和列间距
        layout.minimumLineSpacing = pictureMargin
        layout.minimumInteritemSpacing = pictureMargin
        
        super.init(frame: frame, collectionViewLayout: layout)
        
        //设置数据源代理
        self.dataSource = self
        
        //设置代理
        self.delegate = self
        
        backgroundColor = UIColor.whiteColor()
        
        scrollsToTop = false
       
    
        //注册cell
        registerClass(HMPictureCell.self, forCellWithReuseIdentifier: PICTURECELL)
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //需要根据配图视图的显示的数据的 '数量' 来确定配图视图的大小
    /*
     1. 单张图片按照图片的原比例来显示
     2. 四张图片按照 2 * 2 对称显示
     3. 其他的多张图片 n * 3 形式来显示
     */
    func pictureSize() -> CGSize {
    
        let pictureCount = pictures?.count ?? 0
        
        if pictureCount == 0 {
            return CGSizeZero
        }
        
        //设置流水布局对象
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        
        if pictureCount == 1 {
            //返回原尺寸
            let  size = CGSizeMake(100, 150)
            
            layout.itemSize = size
            
            return size
            
        }
        
        //设置其它情况下的流水布局对象
        layout.itemSize = CGSizeMake(itemWidth, itemWidth)
        
        if pictureCount == 4 {
            
            let width = 2 * itemWidth + pictureMargin
            
            return CGSizeMake(width, width)
        }
        
        //超过四张以上的图片
        //计算行号
        let row = CGFloat((pictureCount - 1) / 3 + 1)
        let maxHeight = row * itemWidth + (row - 1) * pictureMargin
        
         return CGSizeMake(maxWidth, maxHeight)
    }

}

//实现属于源方法 和代理方法
extension HMStatusPickerView : UICollectionViewDataSource , UICollectionViewDelegate{

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictures?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = dequeueReusableCellWithReuseIdentifier(PICTURECELL, forIndexPath: indexPath) as!HMPictureCell
        
//        cell.backgroundColor = randomColor()
        //设置数据
        cell.picture = pictures![indexPath.row]
        
        //返回cell
        return cell
        
        
    }
    
    //实现代理方法
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        let browser = SDPhotoBrowser()
        browser.sourceImagesContainerView = self
        browser.imageCount = pictures?.count ?? 0
        browser.currentImageIndex = indexPath.item
        browser.delegate = self
        browser.show()
        
        
        /*
         SDPhotoBrowser *browser = [[SDPhotoBrowser alloc] init];
         
         browser.sourceImagesContainerView = 原图的父控件;
         
         browser.imageCount = 原图的数量;
         
         browser.currentImageIndex = 当前需要展示图片的index;
         
         browser.delegate = 代理;
         
         [browser show]; // 展示图片浏览器
         */
    }

}

//MARK:实现集成图片检查器的代理方法
extension HMStatusPickerView : SDPhotoBrowserDelegate {
    
    //返回原来现实的小图
    func photoBrowser(browser: SDPhotoBrowser!, placeholderImageForIndex index: Int) -> UIImage! {
        
        //获取点击的cell 
        let indexPath = NSIndexPath(forItem: index, inSection: 0)
        
        let cell = self.cellForItemAtIndexPath(indexPath) as! HMPictureCell
        
        //返回cell对应的image
        return cell.imageView.image
        
    }
    
    
    //返回的高清图片的url地址
    func photoBrowser(browser: SDPhotoBrowser!, highQualityImageURLForIndex index: Int) -> NSURL! {
        
        //获取缩略图的地址
        let urlString = pictures![index].thumbnail_pic
        
        //修改地址中的 thumbnail 为 bimiddle 或者 large
        let middleurlString = urlString?.stringByReplacingOccurrencesOfString("thumbnail", withString: "bmiddle")
        let url = NSURL(string: middleurlString!)
        return url
        
    }

}

//MARK:由于cell只是简单地展示一张图片 所以就在这个文件下 定义一个类 就行
class HMPictureCell : UICollectionViewCell {

    //给cell设置模型
    var picture : HMPictureModel? {
    
        
        didSet {
        
            let url = NSURL(string: self.picture?.thumbnail_pic ?? "")
            
            imageView.sd_setImageWithURL(url)
        
        }
    
    }
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //懒加载
    private lazy var imageView :UIImageView = {
    
    let v = UIImageView()
        
        //设置图片的填充模式
        v.contentMode = .ScaleAspectFill
      
        //
        v.clipsToBounds = true
//        v.layer.masksToBounds = true    masksToBounds 是切割图层用的
        
        return v
        
    
    }()
    
    //设置UI 设置约束
    private func setUpUI() {
    
    addSubview(imageView)
        
        imageView.snp_makeConstraints { (make) in
            
            //四周根父视图对其
            make.edges.equalTo(contentView)
        }
    
    }

}


